{% extends 'base_backend.html' %}
{% load static admin_static i18n %}
{% load zhongbao_admin_filtets %}

{% block header_tail %}
    <link rel="stylesheet" href="{% static 'plugins/select2/select2.css' %}">
    <link rel="stylesheet" href="{% static 'public/CodeMirror/lib/codemirror.css' %}">
    <link rel="stylesheet" href="{% static 'public/CodeMirror/theme/lesser-dark.css' %}">
    <link rel="stylesheet" href="{% static 'public/ComboSelect/css/combo.select.css' %}">
    <link rel="stylesheet" href="{% static 'zhongbao/config/css/main.css' %}">
    <style>
        .select2-container--default .select2-selection--multiple .select2-selection__choice {
            background-color: #3c8dbc;
            border-color: #3c8dbc;
        }
    </style>
{% endblock header_tail %}

{% block section_content %}
    <div>
        <div class="box-header with-border">
            <h3 class="box-title">添加配置</h3>
        </div>
        <!-- form start -->
        <div class="box box-primary">
            <div class="box-body">
                <form id="create_user_form" role="form" action="" method="post"
                      enctype="multipart/form-data">{% csrf_token %}
                    <div>
                        <input class="config-input" readonly="value" type="" style="display: none;" name="task_id" value="{{ task.id }}">
                        {% for field in form %}
                            {% if field.name == 'repeat_times' %}
                                {% if perms.config.view_repeattimes %}
                                    <div class="form-group select-config-div" style="float: left; ">
                                        <label for="" class="control-label"
                                               title="{{ field.help_text }}">{{ field.label }}：</label>
                                        <p>{{ field }}</p>
                                    </div>
                                {% else %}
                                    <div class="form-group select-config-div" style="float: left; display: none">
                                        <label for="" class="control-label"
                                               title="{{ field.help_text }}">{{ field.label }}：</label>
                                        <p>{{ field }}</p>
                                    </div>
                                {% endif %}
                            {% else %}
                                <div class="form-group select-config-div" style="float: left; ">
                                    <label for="" class="control-label"
                                           title="{{ field.help_text }}">{{ field.label }}：</label>
                                    <p>{{ field }}</p>
                                </div>
                            {% endif %}
                        {% endfor %}
                    <!--
                        <div class="form-group select-config-div" style="float: left; width: 80px">
                            <label for="" class="control-label">频道编辑：</label>
                            <p class="btn btn-xs btn-primary" id="config-channel"
                               style="">频道编辑
                            </p>
                        </div>
                        <div class="form-group select-config-div" style="float: left; width: 40% ">
                            <label for="" class="control-label">定时执行：</label>
                            <p>
                                <select class=" select2" multiple="multiple" style="width: 65%" name="clock_time_week"
                                        data-placeholder="Select a State">
                                    {/% for option in add_week_options %}
                                        <option value="{/{ option.val }}">{/{ option.text }}</option>
                                    {/% endfor %}
                                </select>
                                <input class="config-input" type="time" style="width: 20%" name="clock_time_hour" value="">
                            </p>
                        </div>
                    -->
                    </div>
                    <p style="clear: both"></p>
                    {#                    <div>#}
                    {#                        {% for field in form %}#}
                    {#                            {% if field.name not in form_list1 %}#}
                    {#                                <div class="form-group select-config-div" style="float: left; margin-right: 20px;">#}
                    {#                                    <label for="" class="control-label">{{ field.label }}：</label>#}
                    {#                                    <p>{{ field }}</p>#}
                    {#                                </div>#}
                    {#                            {% endif %}#}
                    {#                        {% endfor %}#}
                    {#                        <div class="form-group select-config-div" style="float: left; margin-right: 20px; width: 80px">#}
                    {#                            <label for="" class="control-label">频道编辑：</label>#}
                    {#                            <p class="btn btn-xs btn-primary" id="config-channel"#}
                    {#                               style="">频道编辑#}
                    {#                            </p>#}
                    {#                        </div>#}
                    {#                    </div>#}

                    <!-- 频道编辑弹出窗口-->
                    <div class="modal fade" id="config-channel-editor" tabindex="-1" role="dialog"
                         aria-labelledby="myModalLabel">
                        <div class="modal-dialog modal-lg" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                                            id="close-button0"><span
                                            aria-hidden="true">×</span></button>
                                    <h4 class="modal-title" id="myModalLabel">频道添加</h4>
                                </div>
                                <div class="modal-body">

                                    <div class="form-group">
                                        <label for="txt_departmentname">格式:频道URL#频道名称回车</label>
                                        <textarea name="channel-config-content" class="form-control"
                                                  id="channel-config-content"
                                                  cols="30" style="height: 200px;"></textarea>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" id="btn_close" class="btn btn-default"
                                            data-dismiss="modal"><span
                                            class="glyphicon glyphicon-remove" aria-hidden="true"></span>清空
                                    </button>
                                    <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal">
                                        <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <br style="clear: both">
                        <hr style="margin-top: 0">
                        <div>
                            <input type="file" name="config_file" value="选择文件" style="float: left;">
                            <a href="{{ debug_url }}" target="_blank" id="debug-btn"
                               class="btn btn-primary btn-sm" style="float: left; margin-left: 30px">
                                测试
                            </a>
                        </div>
                        <br style="clear: both">
                        <p style="margin-left: 10px; color: #00a7d0; display: none" id="code-help">鼠标在下方代码框内点击：ctrl+F
                            查找，ctrl+G 下一个</p>
                        <div id="file_show" style="margin-top: 10px">
                            {#                            <pre class="">代码展示区域</pre>#}
                            <textarea name="code" id="code" cols="0" rows="1" class="no-display">代码展示区域</textarea>
                        </div>
                    </div>

                    <!-- /.box-footer -->
                    <div class="box-footer">
                        <button class="btn btn-primary btn-sm" id="_save">确定</button>
                        <button type="submit" class="btn btn-primary btn-sm" id="_submit"
                                style="display: none">sure
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!--alert窗口 -->
    <!--
    <div class="modal fade" id="alert-dom" tabindex="-2" role="dialog"
         aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="alert-title">报警信息：</h4>
                </div>
                <div class="modal-body">

                    <div class="form-group">
                        <p class="form-control"
                           id="alert-content" style="height: 200px;"></p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" id="alert_btn_close" class="btn btn-default" data-dismiss="modal"><span
                            class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭
                    </button>
                    <button type="button" id="alert_btn_submit" class="btn btn-primary" data-dismiss="modal">
                        <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存
                    </button>
                </div>
            </div>
        </div>
    </div>
    -->
{% endblock section_content %}

{% block body_js %}
    {{ block.super }}
    <script src="{% static 'plugins/select2/select2.full.js' %}"></script>
    <script src="{% static 'public/CodeMirror/lib/codemirror.js' %}"></script>
    <script src="{% static 'public/CodeMirror/mode/python/python.js' %}"></script>
    <script src="{% static 'public/ComboSelect/js/jquery.combo.select.js' %}"></script>
    <script src="{% static 'zhongbao/config/js/select_pulic.js' %}"></script>

    <script>
        $(document).ready(function () {

            var file_input = $('input[name="config_file"]');
            var file_show = $('#file_show');
            var textarea = document.getElementById('code');

            var alert_dom = $('#alert-dom');
            var alert_content = $('#alert-content');

            var id_webname = $('#id_webname');  // 网站名称
            var id_url = $('#id_url');  // 网站名称
            var clock_time_select2 = $(".select2").select2({
            });
{#            clock_time_select2.val([1,2]).trigger('change');#}

            {#            function alert(content) {#}
            {#                alert_content.text(content);#}
            {#                alert_dom.modal();#}
            {#                if ($('#alert_btn_close').click()) {#}
            {#                    return false#}
            {#                } else if ($('#alert_btn_submit').click()) {#}
            {#                    return true#}
            {#                }#}
            {#            }#}

            function codem() {
                var editor = CodeMirror.fromTextArea(textarea, {
                    mode: "python",
                    lineNumbers: true,
                    matchBrackets: true,
                    theme: "lesser-dark",
                    parserConfig: {useHTMLKludges: true},
                });
                editor.setOption("extraKeys", {
                    Tab: function (cm) {
                        var spaces = new Array(cm.getOption("indentUnit") + 1).join(" ");
                        cm.replaceSelection(spaces);
                    }
                });
                {#                textarea.innerHTML = editor.getValue();#}
            }

            function readfile() {
                var file_path = file_input.val();
                var files = file_input.prop('files');

                var file_path_split = file_path.split('.');
                var file_formate = file_path_split[file_path_split.length - 1];
                if (file_formate == 'py') {
                    var reader = new FileReader();
                    //将文件以文本形式读入页面
                    reader.readAsText(files[0], 'UTF-8');
                    reader.onload = function (f) {
                        var fileString = f.target.result;
                        // 将网站名称和域名通过上传文件解析后自动传入
                        var site_name_pattern = new RegExp(/self\.siteName\s*?=\s*?["'](.*)["']/);
                        var site_domain_pattern = new RegExp(/self\.site_domain\s*?=\s*?["'](.*)["']/);
                        var site_name = fileString.match(site_name_pattern);
                        var site_domain = fileString.match(site_domain_pattern);
                        if (site_name == null || site_domain == null) {
                            alert('您上传的配置文件缺少网站名称或域名，请检查后重新上传')
                        }else if (site_domain[1].indexOf("/") != -1 || site_domain[1].indexOf("http") != -1){
                            // site_domain[1].indexOf("www.") != -1 ||
                            alert('您上传的配置文件中域名有错误，请检查后重新上传')
                        }else {
                            id_webname.val(site_name[1]);
                            id_url.val(site_domain[1]);
                            // 显示文件
                            // textarea.innerHTML = fileString;
                            $('#code').val(fileString);
                            $('#code-test').val('1');
                            //textarea.val(fileString);
                            codem();
                        }
                    }
                } else {
                    alert('您传入的文件格式为' + file_formate + '，请传入py文件');
                    file_input.val('');
                    textarea.innerHTML = '代码展示区域';
                    return false;
                }
                ;
            };


            file_input.click(function () {
                file_input.val('');
                var textarea_next = file_show.children('div');
                if (textarea_next) {
                    textarea_next.remove();
                }
                ;
                {#                $('#code-help').css('display', 'block');#}

            });
            file_input.change(function () {
                textarea.style.display = 'block';
                textarea.innerHTML = '代码加载中...';
                readfile();
            });

            // 频道编辑弹出框
            var config_channel = $('#config-channel');
            var channel_edtitor = $('#config-channel-editor');
            var channels = $("#channel-config-content");
            config_channel.click(function () {
                channel_edtitor.modal()
            });
            // 保存按钮操作
            function close_channel() {
                var channels_content = channels.val();
                if (channels_content.indexOf('#') < 0 && channels_content.length > 0) {
                    alert('添加的频道格式不正确（缺少英文#），如不需要，请清空后保存或关闭！');
                    return false;
                }
            }

            $('#btn_submit').click(close_channel);
            $('#close-button0').click(close_channel);
            // 关闭按钮操作
            $('#btn_close').click(function () {
                alert('将会清空现有内容！');
                channels.val('');
                return false;
            });

            //测试
            var debug_btn = $('#debug-btn');
            debug_btn.click(function () {
                var codeKey = "codekey";
                var codeTag = "codetag";
                var storage = window.localStorage;
                storage.setItem(codeKey, $('#code').val());
                storage.setItem(codeTag, 1);
            })

        });
    </script>
{% endblock body_js %}